// import utils
import apiRequest from "./request.js";
import { STATISTICS_DATA } from "@/common/constants.js";

/* --------------------------------------------------------------
 *                        Statistics API
 * -------------------------------------------------------------- */

/**
 * 根据查询条件获取统计数据
 * @param {Object} searchData - 查询数据
 * @returns {Promise<Object>} - 查询后的统计数据
 */
async function getStatistics(searchData) {
    try {
        const response = await apiRequest('POST', '/statistics/getStatistics', searchData);

        if (response.code === 200 && response.success) {
            const { startDate, endDate } = searchData;

            // 获取符合条件的统计数据
            const filteredData = Object.keys(STATISTICS_DATA)
                .reduce((result, key) => {
                    const date = STATISTICS_DATA[key];
                    const subscribeKey = key.replace('date', 'subscribe');
                    const subscribe = STATISTICS_DATA[subscribeKey];

                    // 转换 date 字符串为 Date 对象进行比较
                    const currentDate = new Date(date);
                    if (currentDate >= startDate && currentDate <= endDate) {
                        result[key] = date;
                        result[subscribeKey] = subscribe;
                    }
                    return result;
                }, {});

            return { success: true, data: filteredData };

        } else {
            throw new Error('查询统计数据失败');
        }
    } catch (error) {
        console.error('查询统计数据失败:', error);
        throw new Error('查询统计数据失败');
    }
}

export default getStatistics;